package org.znxs.comfriend.adapters;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide; // 用于加载图片

import org.znxs.comfriend.R;
import org.znxs.comfriend.models.Message;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.AllUserList;
import org.znxs.comfriend.utils.LoginUser;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {

    private Context context;
    private List<User> userList;
    private OnItemClickListener listener;

    private LoginUser loginUser;

    public ChatAdapter(Context context, List<User> userList, OnItemClickListener listener) {
        this.context = context;
        this.userList = userList;
        this.listener = listener;
        this.loginUser = LoginUser.getInstance(context);
    }

    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_message_list, parent, false);
        return new ChatViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        User friend = userList.get(position);

        // 绑定用户头像
        Glide.with(context)
                .load(friend.getAvatarUrl()) // 加载头像 URL
                .placeholder(R.drawable.pengyiyan) // 占位符
                .error(R.drawable.error) // 错误占位符
                .into(holder.ivAvatar);

        // 绑定用户名
        holder.tvUsername.setText(friend.getNickname());

        // 绑定最后一条消息（假设从其他地方获取）
        String lastMessage = getLastMessageForUser(friend.getId());
        holder.tvLastMessage.setText(lastMessage);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            listener.onItemClick(friend.getId(), friend.getNickname(), friend.getAvatarUrl());
        });
    }

    @Override
    public int getItemCount() {
        return userList.size();
    }

    /**
     * 获取用户的最后一条消息
     */
    private String getLastMessageForUser(String receiverId) {
        // 获取消息列表
        List<Message> messageList = loginUser.getLoginUser().getMessageHashMap().get(receiverId);

        // 检查列表是否为空或为 null
        if (messageList == null || messageList.isEmpty()) {
            Log.w("ChatAdapter", "Message list is empty or null");
            return "No messages"; // 返回默认值
        }

        // 获取最后一条消息
        Message lastMessage = messageList.get(messageList.size() - 1);

        // 检查消息内容是否为空
        if (lastMessage.getContent() == null || lastMessage.getContent().isEmpty()) {
            Log.w("ChatAdapter", "Last message content is null or empty");
            return "Empty message"; // 返回默认值
        }

        // 返回最后一条消息的内容
        return lastMessage.getContent();
    }

    static class ChatViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tvUsername;
        TextView tvLastMessage;

        public ChatViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvLastMessage = itemView.findViewById(R.id.tv_last_message);
        }
    }

    /**
     * 更新数据
     */
    public void updateData(List<User> newData) {
        this.userList = newData;
        notifyDataSetChanged();
    }

    public interface OnItemClickListener {
        void onItemClick(String userId, String userName, String userAvatarUrl);
    }
}
